package com.zhuzi.controller;

import cn.hutool.extra.servlet.ServletUtil;
import com.zhuzi.utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * @author zhuzi
 * 2022/9/5 11:04
 */
@Slf4j()
@RestController
@RequestMapping("ip")
public class IpController {

    @Value("${serviceName:默认}")
    public String serviceName;

    @Value("#{${test.maps}}")
    private Map<String, String> maps;

    @GetMapping
    public ResponseEntity<String> now(HttpServletRequest request) {

        String clientIP = ServletUtil.getClientIP(request, null);
        System.out.println(maps);

        String baseUrl = RequestUtils.getBaseUrl(request);
        log.info("baseUrl: " + baseUrl);
        return ResponseEntity.ok(clientIP + serviceName);
    }


    @GetMapping("/io/{id}")
    public void bayPicByFid(@PathVariable String id, HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        log.info("请求图片-{}", id);

        String file = ResourceUtils.getFile("classpath:static/img/p_big" + id + ".jpg").getPath();
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        response.getOutputStream().write(FileUtils.readFileToByteArray(new File(file)));

    }

    //
    @GetMapping(value = "/sp/{id}", produces = {MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE})
    @ResponseBody
    public byte[] pics(@PathVariable String id, HttpServletResponse response) throws IOException {

        log.info("请求图片-{}", id);

        String file = ResourceUtils.getFile("classpath:static/img/p_big" + id + ".jpg").getPath();
        return FileUtils.readFileToByteArray(new File(file));
    }
}
